

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:video_compress/video_compress.dart';
import 'package:path_provider/path_provider.dart';
import 'package:http/http.dart'  as http;

class VideoUploader {
  bool isUploading = false;
  String? content;

  Future<void> convertVideoAndUpload(String content) async {
    this.content  = content;
    isUploading = true;

    // 从相册选择视频
    final picker = ImagePicker();
    final pickedFile = await picker.pickVideo(source:  ImageSource.gallery);
    if (pickedFile == null) {
      isUploading = false;
      print('未选择视频');
      return;
    }

    final videoFile = File(pickedFile.path);

    // 视频转码
    MediaInfo? mediaInfo = await VideoCompress.compressVideo(
      videoFile.path,
      quality: VideoQuality.DefaultQuality,
      deleteOrigin: false,
    );

    if (mediaInfo == null) {
      isUploading = false;
      print('转码失败');
      return;
    }

    final compressedFile = File(mediaInfo.path!);
    final fileSize = await compressedFile.length();

    // 检查文件大小是否超过50MB
    if (fileSize > 50 * 1024 * 1024) {
      isUploading = false;
      print('压缩后的文件大小不能超过50M');
      return;
    }

    // 生成文件名
    final fileName = DateTime.now().millisecondsSinceEpoch.toString();

    // 上传视频
    await uploadVideo(compressedFile, fileName, content);
  }

  Future<void> uploadVideo(File videoFile, String fileName, String content) async {
    try {
      final url = Uri.parse('your_upload_url');
      var request = http.MultipartRequest('POST', url);
      request.files.add(await  http.MultipartFile.fromPath('video',  videoFile.path));
      request.fields['fileName']  = fileName;
      request.fields['content']  = content;

      var response = await request.send();
      if (response.statusCode  == 200) {
        print('上传成功');
      } else {
        print('上传失败');
      }
    } catch (e) {
      print('上传出错: $e');
    } finally {
      isUploading = false;
    }
  }
}


/*


上传视频oc代码

// 视频转码mp4
- (void)convertVideo:(NSArray *)videoArr andContent:(NSString *)content{

    self.content = content;

    self.isUploading = YES;

//    [self ShowLoadingWithView:self.view Orgin:0 ViewHeight:0 loadtype:2 loadStr:NSLocalizedString(@"正在压缩...", nil)];
//    [[KHUnTouchLoading sharedInstance] ShowLoadingWithStr:NSLocalizedString(@"正在压缩...", nil) loadingTime:120];
    PHAsset *phAsset = videoArr.firstObject;

    PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
    options.version = PHVideoRequestOptionsVersionCurrent;
    options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
    options.networkAccessAllowed = YES;//是否允许从icloud获取图片
    PHImageManager *manager = [PHImageManager defaultManager];
    [manager requestAVAssetForVideo:phAsset options:options resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {

        if (asset == nil) {
            [[KHUnTouchLoading sharedInstance] HideLoading];
            showToast(NSLocalizedString(@"上传失败", nil));
            self.isUploading = NO;

            return;
        }

        NSString *fileName = CRString(@"%@",CRCurrentTimestamp());

        dispatch_async(dispatch_get_main_queue(), ^{
            AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetHighestQuality];
            NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:asset];
            if (@available(iOS 11.0, *)) {
                if ([compatiblePresets containsObject:AVAssetExportPresetHEVC1920x1080]) {
                    exportSession = [[AVAssetExportSession alloc] initWithAsset:asset presetName:AVAssetExportPresetHEVC1920x1080];
                }
            }
            NSString *savePath = CRString(@"%@%@.mp4", NSTemporaryDirectory(), fileName);
            if ([[NSFileManager defaultManager] fileExistsAtPath:savePath]) {
                [[NSFileManager defaultManager] removeItemAtPath:savePath error:nil];
            }
            exportSession.outputURL = [NSURL fileURLWithPath:savePath];
            exportSession.shouldOptimizeForNetworkUse = true;

            NSArray *supportedTypeArray = exportSession.supportedFileTypes;
            if ([supportedTypeArray containsObject:AVFileTypeMPEG4]) {
                exportSession.outputFileType = AVFileTypeMPEG4;
            } else if (supportedTypeArray.count == 0) {
                showToast(NSLocalizedString(@"不支持的文件类型", nil));
                self.isUploading = NO;
                return;
            } else {
                exportSession.outputFileType = [supportedTypeArray objectAtIndex:0];
            }

//            exportSession.videoComposition = [self getVideoComposition:asset];
            [exportSession exportAsynchronouslyWithCompletionHandler:^{
                if ([exportSession status] == AVAssetExportSessionStatusCompleted) {
                    if ([[NSFileManager defaultManager] attributesOfItemAtPath:savePath error:nil].fileSize > 50 * 1024 * 1024) {
                        [[KHUnTouchLoading sharedInstance] HideLoading];
                        showToast(NSLocalizedString(@"压缩后的文件大小不能超过50M", nil));
                        self.isUploading = NO;

                    }
                    else {
                        [[KHUploadManager sharedInstance] uploadVideo:fileName andContent:content];
                    }
                }
                else {
                    // 如果文件本身就是mp4格式，就直接上传
                    AVURLAsset *urlAsset = (AVURLAsset *)asset;
                    if ([urlAsset.URL.absoluteString hasSuffix:@"MP4"] || [urlAsset.URL.absoluteString hasSuffix:@"mp4"]) {
                        NSString *savePath = CRString(@"%@%@.mp4", NSTemporaryDirectory(), fileName);
                        if ([[NSFileManager defaultManager] fileExistsAtPath:savePath]) {
                            [[NSFileManager defaultManager] removeItemAtPath:savePath error:nil];
                        }
                        NSData *data = [NSData dataWithContentsOfURL:urlAsset.URL];
                        [data writeToFile:savePath atomically:YES];

                        if ([[NSFileManager defaultManager] attributesOfItemAtPath:savePath error:nil].fileSize > 50 * 1024 * 1024) {
                            [[KHUnTouchLoading sharedInstance] HideLoading];
                            showToast(NSLocalizedString(@"压缩后的文件大小不能超过50M", nil));
                            self.isUploading = NO;

                        }
                        else {
                            [[KHUploadManager sharedInstance] uploadVideo:fileName andContent:content];

                        }
                    }
                    else {
                        [[KHUnTouchLoading sharedInstance] HideLoading];
                        showToast(NSLocalizedString(@"压缩失败", nil));
                        self.isUploading = NO;

                    }
                }
            }];
        });
    }];
}



*/